package com.softeem.score.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softeem.score.common.exception.MyException;
import com.softeem.score.manager.mapper.SysRoleMapper;
import com.softeem.score.manager.mapper.SysRoleMenuMapper;
import com.softeem.score.manager.mapper.SysUserMapper;
import com.softeem.score.manager.mapper.SysUserRoleMapper;
import com.softeem.score.manager.service.SysRoleService;
import com.softeem.score.model.entity.system.SysRole;
import com.softeem.score.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2024-02-14
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public PageInfo<SysRole> findByPage(String roleName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);// 开启分页
        List<SysRole> sysRoleList = sysRoleMapper.findByRoleName(roleName);// 查询数据
        PageInfo<SysRole> pageInfo = new PageInfo(sysRoleList);// 封装分页数据
        return pageInfo;
    }

    @Override
    public void saveSysRole(SysRole sysRole) {
        sysRoleMapper.saveSysRole(sysRole.getName(), sysRole.getDescription());
    }

    @Override
    public void updateSysRole(SysRole sysRole) {
        sysRoleMapper.updateSysRole(sysRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long roleId) {
        // 判断是否有用户拥有该角色
        if (sysUserMapper.existsUserWithRoleId(roleId)) {
            throw new MyException(ResultCodeEnum.USER_EXISTS_NOTDELETE);
        }
        // 判断是否为该角色分配了菜单权限
        if (sysRoleMenuMapper.existsRoleMenuWithRoleId(roleId)) {
            // 如果有分配了菜单权限，可以选择拒绝删除角色，或者先将与该角色相关的菜单权限删除
            // 这里选择先删除角色与菜单的关联关系
            sysRoleMenuMapper.deleteByRoleId(roleId);
        }
        // 删除角色
        sysRoleMapper.delete(roleId);
    }

    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        // 查询所有的角色数据
        List<SysRole> sysRoleList = sysRoleMapper.findAllRoles();
        // 查询当前登录用户的角色数据
        List<Long> sysRoles = sysUserRoleMapper.findSysUserRoleByUserId(userId);
        // 构建响应结果数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("allRolesList", sysRoleList);
        resultMap.put("sysUserRoles", sysRoles);
        return resultMap;
    }
}
